package org.swim.session;

import java.util.Collection;
import java.util.Iterator;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swim.entity.User;

@Stateless
@RemoteBinding(jndiBinding="LoginManagerRemote")
public class LoginManager implements LoginManagerRemote {

	/**
	 * Manager degli entity beans. Permette di interagire direttamente col database inserendo e ricercando dati
	 */
	@PersistenceContext(unitName="swim") private EntityManager manager;
	
	@Override
	public User verifyLogin(String mail, String password) throws EntityNotFoundException {
		
		Query q=manager.createQuery("SELECT OBJECT(u) FROM User AS u WHERE u.email=:mail");
		q.setParameter("mail", mail);
		@SuppressWarnings("unchecked")
		Collection<User> coll = (Collection<User>) q.getResultList();
		
		Iterator<User> itar = coll.iterator();
		
		while (itar.hasNext())
		{
			User u = (User) itar.next();
			if(u.getPassword().equals(password))
			{
				return u;
			}
		}
		return null;
	
	}
	
	
}
